﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using rehabilitation.Data;
using rehabilitation.Models;

namespace rehabilitation.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class VisitController : ControllerBase
    {
        private readonly AppDbContext _context;

        public VisitController(AppDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 1. 通过医生 ID 查询随访记录（分页）
        /// </summary>
        [HttpGet("listByDoctor/{doctorId}")]
        public async Task<IActionResult> GetVisitsByDoctor(int doctorId, int pageIndex = 1, int pageSize = 10)
        {
            if (pageIndex < 1 || pageSize < 1)
            {
                return BadRequest("分页参数无效");
            }

            var query = _context.Visits
                .Where(v => v.DoctorId == doctorId)
                .OrderByDescending(v => v.Time);

            int totalRecords = await query.CountAsync();
            var visits = await query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();

            return Ok(new
            {
                TotalRecords = totalRecords,
                PageIndex = pageIndex,
                PageSize = pageSize,
                Data = visits
            });
        }

        /// <summary>
        /// 2. 根据患者姓名查询随访记录（分页，连表查询）
        /// </summary>
        [HttpGet("listByPatientName")]
        public async Task<IActionResult> GetVisitsByPatientName(string patientName, int pageIndex = 1, int pageSize = 10)
        {
            if (string.IsNullOrEmpty(patientName))
            {
                return BadRequest("患者姓名不能为空");
            }

            var query = from v in _context.Visits
                        join p in _context.Patients on v.PatientId equals p.Id
                        where p.Name.Contains(patientName)
                        orderby v.Time descending
                        select new
                        {
                            v.Id,
                            PatientName = p.Name,
                            v.DoctorId,
                            v.Time,
                            v.Content
                        };

            int totalRecords = await query.CountAsync();
            var visits = await query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();

            return Ok(new
            {
                TotalRecords = totalRecords,
                PageIndex = pageIndex,
                PageSize = pageSize,
                Data = visits
            });
        }

        /// <summary>
        /// 3. 删除随访记录
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteVisit(int id)
        {
            var visit = await _context.Visits.FindAsync(id);
            if (visit == null)
            {
                return NotFound("随访记录不存在");
            }

            _context.Visits.Remove(visit);
            await _context.SaveChangesAsync();
            return Ok("随访记录已删除");
        }

        /// <summary>
        /// 4. 编辑随访记录
        /// </summary>
        [HttpPut("update")]
        public async Task<IActionResult> UpdateVisit([FromBody] Visit visit)
        {
            var existingVisit = await _context.Visits.FindAsync(visit.Id);
            if (existingVisit == null)
            {
                return NotFound("随访记录不存在");
            }

            existingVisit.Time = visit.Time;
            existingVisit.Content = visit.Content;

            await _context.SaveChangesAsync();
            return Ok("随访记录已更新");
        }
    }
}
